<?php
namespace app\services;
use app\models\MobileAdspace;
use app\models\ResourceAppAdspaceMap;
use app\models\ResourceApp;
use app\models\Material;

use app\utils\Functions as F;

class AppService extends BaseService
{
    public function getAppList()
    {
        //$apps = $this->getAll('ResourceApp', ['status' => 1]);
        $apps = ResourceApp::find()->where(['status' => 1])
            ->orderBy(['last_update' => SORT_DESC])
            ->asArray()->indexBy('id')->all();
        $appAdMaps = $this->getAll('ResourceAppAdspaceMap', ['status' => 1]);
        $appAds = [];
        if ($appAdMaps) {
            $adIdAppMap = array_column($appAdMaps, 'app_id', 'adspace_id');
            $appAdIds = array_column($appAdMaps, 'adspace_id');
            $appAds = $this->getAll('MobileAdspace', ['id' => $appAdIds]);
        }
        $appDims = [];
        foreach ($appAds as $adid => $ad) {
            $adId = $ad['id'];
            $adSize = $ad['ext_size'];
            $appId = $adIdAppMap[$adId];
            $app = $apps[$appId];
            if (isset($app['size'])) {
                $newSizeItem = explode(',', $adSize);
                $app['size'] = array_merge($app['size'], $newSizeItem);
            } else {
                $app['size'] = explode(',', $adSize);
            }
            $app['size'] = array_unique($app['size']);
            asort($app['size']);
            $form = $ad['size_form'];
            $app['allowFormat'][] = $form;
            $app['app_type'] = 'APP';
            if ($app['type'] == 2)  $app['app_type'] = 'WAP';
            $type = $ad['format_list'];
            if (!isset($app['type'])) {
                $app['type'] = $type;
            } else {
                $app['type'] .= ','.$type;
            }
            $apps[$appId] = $app;
        }

        $maps = [
            'id'            => 'id',
            'name'          => 'name',
            'app_type'      => 'app_type',
            'floor_price'   => 'floor_price',
            'ceiling_price' => 'ceiling_price',
            'size'          => ['id', 'if (!isset($size)) return []; 
                                $v = array_values($size); 
                                return $v;'],
            'allowFormat'   => ['id', '
                                if (!isset($allowFormat)) return "信息流";
                                $v = $allowFormat;
                                    $k = [];
                                if(in_array(0, $v)) $k[] = "下部浮层";
                                if(in_array(1, $v)) $k[] = "Web Banner";
                                if(in_array(2, $v)) $k[] = "App Banner";
                                if(in_array(3, $v)) $k[] = "开屏";
                                if(in_array(4, $v)) $k[] = "插屏";
                                if(in_array(5, $v)) $k[] = "信息流";
                                return implode(", ", $k);
                                '],
            'type'          => ['id', 'if(!isset($type)) return "JPG, PNG";
                                $types = explode(",", $type); 
                                $k = ["JPG, PNG"];
                                if (in_array(1, $types)) $k[] = "JPG, PNG";
                                if (in_array(2, $types)) $k[] = "GIF";
                                if (in_array(3, $types)) $k[] = "SWF";
                                if (in_array(4, $types)) $k[] = "TXT";
                                if (in_array(5, $types)) $k[] = "FLV";
                                if (in_array(6, $types)) $k[] = "MP4";
                                $k = array_unique($k);
                                return implode(", ", $k);
                                '],
            'modifiedDate'   => 'last_update',
        ];
        $apps = $this->fieldsMap($maps, $apps);//, ['cates' => $cates]);
        return $apps;
    }

    public function trySave($app)
    {
        $on = [];
        $name = $app['name'];
        $isNew = true;
        if (isset($app['id']) && $app['id']) {
            $on = ['id' => $app['id']];
            $isNew = false;
        } else {
            unset($app['id']);
            $on['name'] = $name;
        }
        $nameExists = ResourceApp::find()->where(['name' => $name])->one();
        if ($nameExists && $isNew) $this->ng('App already exits!');
        $app['adspace_image'] = $this->getImageUrls($app['upload_material']);
        unset($app['adspace_ids']);
        unset($app['upload_material']);
        $save = $this->saveOn('ResourceApp', $on, $app);
        return $save;
    }

    public function saveAppAdspaceMap($appId, $adspaceIds)
    {
        $saved = true;
        $this->update('ResourceAppAdspaceMap', ['app_id' => $appId]);//, $on);
        foreach ($adspaceIds as $adspaceId) {
            $on = ['app_id' => $appId, 'adspace_id' => $adspaceId];
            $data = $on;
            $data['status'] = 1;
            $isSaved = $this->saveOn('ResourceAppAdspaceMap', $on, $data);
            if (!$isSaved || !isset($isSaved['id'])) {
                $saved = false;
            }
        }
        return $saved;
    }

    public function getImageUrls($ids)
    {
        $path = 'admath/apps/';
        $newId = [];
        $oldPic = [];
        foreach ($ids as $id) {
            if (is_numeric($id)) $newId[] = $id;
            else $oldPic[] = $id;
        }
        $materials = Material::find()->select(["concat('$path', name) name"])
            ->where(['id' => $newId])
            ->asArray()->all();
        $materials = array_column($materials, 'name');
        $materials = array_merge($oldPic, $materials);
        return implode(';', $materials);
    }

    public function getAppAdspaces($appId)
    {
        $appAdspaceIds = ResourceAppAdspaceMap::find()->select(['adspace_id'])
            ->where(['status' => 1, 'app_id' => $appId])
            ->asArray()->all();
        $appAdspaceIds = array_column($appAdspaceIds, 'adspace_id');
        if (!$appAdspaceIds) return [];
        $ads = MobileAdspace::find()->select(['id', 'name'])
            ->where(['id' => $appAdspaceIds])
            ->asArray()->all();
        return $ads;
    }

    public function getUnbindAdspace($key='', $type=1)
    {
        $bindAds = ResourceAppAdspaceMap::find()->select(['adspace_id'])
                ->where(['status' => 1])->asArray()->all();
        $bindAds = array_column($bindAds, 'adspace_id');
        $on = 'status = 0 ';
        $type == 1 && $on .= ' and type > 1 ';
        $type == 2 && $on .= ' and type = 1 ';
        if ($bindAds) {
            $on .= ' and id not in (' . implode(',', $bindAds) .')';
        }
        if ($key) {
            $on .= " and name like '%$key%' ";
        }
        $unbindAds = MobileAdspace::find()->select(['id', 'name text'])
                    ->where($on)->asArray()->all();
        return $unbindAds;
    }

    public function getAdspaceSizeAndFormats($adspaceIds)
    {
        $packService = new PackService();
        return $packService->getAdspaceSizeAndExtsByAdspaceIds($adspaceIds);
    }

    public function addMaterial($fileInfo)
    {
        if (is_array($fileInfo)) {
            $material = $this->addNewMaterialRecord($fileInfo);
            $fileInfo = $this->M('Material', $material['id']);
            $fileInfo['size'] = number_format($fileInfo['size']/1024, 2).'k';
        }
        return $fileInfo;
    }

    public function addNewMaterialRecord($fileInfo, $advertiserId=99999)
    {
        foreach ($fileInfo as $info) {
            $data = $info;
            $data['advertiser_id'] = $advertiserId;
            $data['ext'] = strtolower($data['extension']);
            $data['name'] = $data['savename'];
            $data['path'] = $data['savepath'];
            // 获取 session user id
            $data['upload_by'] = $this->S('user_id');
            $data['upload_ip'] = F::get_client_ip();
            return $this->save('Material', $data);
        }
    }

    public function uploadAdsPic()
    {
        $ext = ['jpg','png'];
        $dir = \Yii::$app->params['upload']['appPath'];
        $fileInfo = $this->upload(false, $dir);
        if (is_array($ext)) {
            if (!in_array(strtolower($fileInfo[0]['extension']), $ext)) {
                $this->NG('File type not allowed!');
            }
        }
        // upload done, return fileinfo
        $result = $this->addMaterial($fileInfo);
        if (!is_array($result)) {
            $this->NG($result);
        }
        if (is_array($result)) {
            $result = $this->getRef($result);
            if ($result['table']['judgeInfo']  == $this->t('creative', 'unqualified')) {
                $this->NG($this->t('creative', 'Material is not qualified!'));
            }
            $this->OK($this->t('creative', 'Material uploaded!'), 'ok', $result);
        }
        $this->NG($result);
    }

    public function getRef($result)
    {
        if (is_array($result)) {
            $id = $result['id'];
            $user = $this->M('User', $result['upload_by']);
            $table = [
                'name' => $result['name'],
                'size' => $result['size'],
                'date' => $result['last_update'],
                'judgeInfo' => 'qualified',
                'updater' => $user['name'],
            ];
            $preview = [
                'width' => $result['width'],
                'height' => $result['height'],
                'type' => $result['ext'],
                'address' => $this->getAppPicUrl($result['name']),
            ];
        }
        return ['id' => $id, 'table' => $table, 'preview' => $preview];
    }

    public function getAppPicUrl($name) {
        $PIC = '/admath/apps/'.$name;
        return $this->getSiteBaseUrl().$PIC;
    }

}//end
